package com.qingke.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qingke.annotation.SkipSecurityCheck;
import com.qingke.pojo.Classes;
import com.qingke.pojo.FeedbackRecord;
import com.qingke.pojo.GraduationRecord;
import com.qingke.pojo.Student;
import com.qingke.pojo.StudentAccount;
import com.qingke.pojo.UploadFile;
import com.qingke.service.ClassService;
import com.qingke.service.FeedbackRecordService;
import com.qingke.service.GraduationRecordService;
import com.qingke.service.StudentService;
import com.qingke.service.UploadFileService;

@Controller
@RequestMapping("/student")
public class StudentController {
	private static Logger logger = Logger.getLogger(StudentController.class);
	private Map<String, Object> map;
	@Autowired
	private StudentService studentService;
	@Autowired
	private UploadFileService uploadFileService;
	@Autowired
	private FeedbackRecordService feedbackRecordService;
	@Autowired
	private GraduationRecordService graduationRecordService;
	@Autowired
	private ClassService classService;

	@RequestMapping("getStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map getStudent(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student student = (Student) se.getAttribute("user");
		logger.info("get student:" + student);
		map.put("student", student);
		return map;
	}

	@RequestMapping("upadteStudentMessage")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateStudentMessage(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student student = (Student) se.getAttribute("user");
		String studentName = request.getParameter("student_name");
		String studentId = request.getParameter("student_id");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String school = request.getParameter("school");
		String major = request.getParameter("major");
		String sex = request.getParameter("sex");
		String education = request.getParameter("education");
		logger.info("get student_name:" + studentName + "student_id:" + studentId + "email:" + email + "phone:" + phone
				+ "school:" + school + "major:" + major + "sex:" + sex + "education:" + education);
		if (!studentId.equals(student.getStudentNumber())) {
			map.put("isSame", "no");
		} else {
			student.setName(studentName);
			student.setEmail(email);
			student.setPhone1(phone);
			student.setSchool(school);
			student.setMajor(major);
			student.setGender(sex);
			student.setEducation(education);
			int count = studentService.updateStudentByPrimaryKey(student);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "failed");
			}
		}
		return map;
	}

	@RequestMapping("updateStudentPassword")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateStudentPassword(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student student = (Student) se.getAttribute("user");
		String oldPassword = request.getParameter("old_password");
		String newPassword = request.getParameter("new_password");
		String confrimPassword = request.getParameter("confirm_password");
		logger.info("get StudentPassword:old_password" + oldPassword + ",new_password=" + newPassword
				+ ",confirm_password=" + confrimPassword);
		StudentAccount studentAccount = studentService.getStudentAccountById(student.getId());
		if (!oldPassword.equals(studentAccount.getPassword())) {
			map.put("isExsit", "false");
		} else if (!newPassword.equals(confrimPassword)) {
			map.put("equal", "false");
		} else {
			studentAccount.setPassword(newPassword);
			int count = studentService.updateStudentAccountByPrimaryKey(studentAccount);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "false");
			}
		}
		Collection<Object> c = map.values();
		Iterator it = c.iterator();
		for (; it.hasNext();) {
			System.out.println(it.next());
		}
		return map;
	}

	@RequestMapping("uploadFile")
	@SkipSecurityCheck
	@ResponseBody
	public Map uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student student = (Student) se.getAttribute("user");
		logger.info("get file:" + file);
		String fileName = request.getParameter("file_name");
		if("".equals(fileName)){
			fileName=file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf("."));
		}
		logger.info("get file_name:" + fileName);
		if (!file.isEmpty()) {
			// 取文件格式后
			String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
			Date date = new Date();
			Timestamp timeStamp = new Timestamp(date.getTime());
			logger.info("get date:" + date + ",timeStamp:" + timeStamp);
			String file_name = fileName + type;
			String file_path = request.getSession().getServletContext().getRealPath("upload");
			File targetFile = new File(file_path, file_name);
			logger.info("get type=" + type + ",timeStamp=" + timeStamp + ",file_name=" + file_name + ",file_path="
					+ file_path + "targetFile=" + targetFile);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存文件
			try {
				file.transferTo(targetFile);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			UploadFile uploadFile = new UploadFile();
			uploadFile.setFileName(file_name);
			uploadFile.setUploadDate(timeStamp);
			uploadFile.setUploaderNumber(student.getStudentNumber());
			uploadFile.setUploaderName(student.getName());
			uploadFile.setFileAddress("/" + file_name);
			uploadFile.setIsDeleted(false);
			int count = uploadFileService.saveUploadFile(uploadFile);
			if (count > 0) {
				map.put("upload", "success");
			} else {
				map.put("upload", "failed");
			}
		}
		return map;
	}

	@RequestMapping("downloadFile")
	@SkipSecurityCheck
	public String downloadFile(@RequestParam("fileName") String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		String ctxPath = request.getSession().getServletContext().getRealPath("upload");
		File file = new File(ctxPath, fileName);
		String downloadPath = ctxPath + "\\" + fileName;
		logger.info("get fileName:" + fileName + ",ctxPath:" + ctxPath + ",file_path=" + file);
		System.out.println(file.exists());
		if (file.exists()) {

			response.setContentType("application/force-download;");
			response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

			byte[] buffer = new byte[2048];
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			FileInputStream fis=null;
			try {
				fis=new FileInputStream(downloadPath);
				bis = new BufferedInputStream(fis);
				bos = new BufferedOutputStream(response.getOutputStream());
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buffer, 0, buffer.length))) {
					bos.write(buffer, 0, bytesRead);
				}
				logger.info("get bis=" + bis + ",bos=" + bos + ",bytesRead=" + bytesRead);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}

	@RequestMapping("listUploadFile")
	@SkipSecurityCheck
	@ResponseBody
	public Map listUploadFile(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student student = (Student) se.getAttribute("user");
		List<UploadFile> uploadFile = new ArrayList();
		List<UploadFile> uploadFiles = uploadFileService.listUploadFileByUploaderNumber(student.getStudentNumber());
		logger.info("list uploadFile" + uploadFiles);
		if (uploadFiles != null) {
			for (UploadFile uf : uploadFiles) {
				logger.info("get uploadFile:" + uf);
				if (!uf.getIsDeleted()) {
					uploadFile.add(uf);
				}
			}
		} else {
			uploadFile.add(null);
		}
		map.put("uploadFile", uploadFile);
		return map;

	}

	@RequestMapping("listClassmate")
	@SkipSecurityCheck
	@ResponseBody
	public Map listClassmate(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student stu = (Student) se.getAttribute("user");
		List<Student> unEmployedStudent = new ArrayList();
		List<Student> employedStudent = new ArrayList();
		List<Student> students = studentService.listStudent();
		List<GraduationRecord> graduationRecord = graduationRecordService.listGraduationRecord();
		for (Student st : students) {
			logger.info("list student:" + st);
			if (!st.getIsDeleted() && stu.getClassId() == st.getClassId()) {
				System.out.println(!st.getIsDeleted() && stu.getClassId() == st.getClassId());
				if (!graduationRecord.isEmpty()) {
					for (GraduationRecord gr : graduationRecord) {
						logger.info("list interviewSituationRecord:" + gr);
						if (st.getId() == gr.getStudentId() && !"".equals(gr.getCompany())) {
							employedStudent.add(st);
						} else {
							unEmployedStudent.add(st);
						}
					}
				} else {
					unEmployedStudent.add(st);
				}
			}
			map.put("unEmployedStudent", unEmployedStudent);
			map.put("employedStudent", employedStudent);
		}
		return map;
	}

	@RequestMapping("listClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listClass(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		List<Classes> clazz = classService.listClass();
		List<Classes> classes = new ArrayList();
		if (!clazz.isEmpty()) {
			for (Classes clas : clazz) {
				if (!clas.getIsDeleted()) {
					logger.info("get class=" + clas);
					classes.add(clas);
				}
			}
			map.put("classes", classes);
		} else {
			map.put("classes", "");
		}
		return map;
	}

	@RequestMapping("listPreviousStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map listPreviousStudent(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student stu = (Student) se.getAttribute("user");
		String className = request.getParameter("className");
		List<Student> unEmployedStudent = new ArrayList();
		List<Student> employedStudent = new ArrayList();
		List<Student> students = studentService.listStudent();
		List<GraduationRecord> graduationRecord = graduationRecordService.listGraduationRecord();
		if ("全部班级".equals(className)) {
			for (Student st : students) {
				logger.info("list student:" + st);
				if (!st.getIsDeleted()) {
					if (!graduationRecord.isEmpty()) {
						for (GraduationRecord gr : graduationRecord) {
							logger.info("list interviewSituationRecord:" + gr);
							if (st.getId() == gr.getStudentId() && !"".equals(gr.getCompany())) {
								employedStudent.add(st);
							} else {
								unEmployedStudent.add(st);
							}
						}
					} else {
						unEmployedStudent.add(st);
					}
				}
				map.put("unEmployedStudent", unEmployedStudent);
				map.put("employedStudent", employedStudent);
				map.put("graduationRecord", graduationRecord);
			}
		} else {
			for (Student st : students) {
				logger.info("list student:" + st);
				if (!st.getIsDeleted() && st.getClazz().getClassName().equals(className)) {
					if (!graduationRecord.isEmpty()) {
						for (GraduationRecord gr : graduationRecord) {
							if (st.getId() == gr.getStudentId() && !"".equals(gr.getCompany())) {
								employedStudent.add(st);
							} else {
								unEmployedStudent.add(st);
							}
						}
					} else {
						unEmployedStudent.add(st);
					}
				}
				map.put("unEmployedStudent", unEmployedStudent);
				map.put("employedStudent", employedStudent);
				map.put("graduationRecord", graduationRecord);
			}
		}
		return map;
	}

	@RequestMapping("feedback")
	@SkipSecurityCheck
	@ResponseBody
	public Map feedback(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Student student = (Student) se.getAttribute("user");
		String type = request.getParameter("type");
		String content = request.getParameter("content");
		Date date = new Date();
		Timestamp timeStamp = new Timestamp(date.getTime());
		logger.info("get type=" + type + ",content=" + content + ",timeStamp=" + timeStamp);
		FeedbackRecord feedbackRecord = new FeedbackRecord();

		feedbackRecord.setStudentId(student.getId());
		feedbackRecord.setDate(timeStamp);
		feedbackRecord.setFeedbackType(type);
		feedbackRecord.setContent(content);
		feedbackRecord.setIsDeleted(false);
		int count = feedbackRecordService.saveFeedbackRecord(feedbackRecord);
		if (count > 0) {
			map.put("feedback", "success");
		} else {
			map.put("feedback", "failed");
		}
		return map;
	}

}
